import { Form, Modal, Input, message } from 'antd';
import React, { useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import http from '@/services/request';

const UserForm = ({ formRef }) => (
  <Form
    name="basic"
    labelCol={{ span: 4 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    autoComplete="new-password"
    ref={formRef}
  >
    <Form.Item
      label="用户名"
      name="username"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>

    <Form.Item
      label="密码"
      name="password"
      rules={[{ required: true, message: 'Please input your password!' }]}
    >
      <Input.Password />
    </Form.Item>
  </Form>
);

const LoginModal = ({ visible, closeModal }) => {
  const formRef: any = useRef();
  const Navigator = useNavigate();
  const handleOk = () => {
    formRef.current.validateFields().then(form => {
        http.post("/node/users/register", form).then((result: any) => {
            if (result?.code === 200) {
                message.success('注册成功！');
                closeModal();
                Navigator('/cultivation');
            } else {
                message.error('注册失败！请重试！');
            }
        })
    });
  };
  return (
    <Modal
      title="注册"
      visible={visible}
      onOk={handleOk}
      onCancel={closeModal}
      centered
    >
      <UserForm formRef={formRef} />
    </Modal>
  );
};

export default LoginModal;
